/*
 * @Descripttion: 
 * @version: 
 * @Author: lily
 * @Date: 2021-05-21 17:39:02
 * @LastEditors: lily
 * @LastEditTime: 2021-05-21 17:53:44
 */
/*
 * @lc app=leetcode.cn id=59 lang=javascript
 *
 * [59] 螺旋矩阵 II
 */

// @lc code=start
/**
 * @param {number} n
 * @return {number[][]}
 */
//  思想：
//  同54题

//  复杂度：O(n^2) O(1)

var generateMatrix = function (n) {
    let count = 1
    let top = 0, bottom = n - 1, left = 0, right = n - 1
    let res = Array.from(new Array(n), () => new Array(n).fill(0))
    while (top <= bottom && left <= right) {
        for (let i = left; i <= right; i++) res[top][i] = count++
        top++
        for (let i = top; i <= bottom; i++) res[i][right] = count++
        right--
        if (top > bottom || left > right) break
        for (let i = right; i >= left; i--) res[bottom][i] = count++
        bottom--
        for (let i = bottom; i >= top; i--) res[i][left] = count++
        left++
    }
    return res
};
// @lc code=end

console.log(generateMatrix(20));